package com.xzx.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/11/5 15:40
 */
@Slf4j
public class WebSocketServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ChannelFuture channelFuture = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler())
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler());
                            // ws基于http
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 支持大数据,大数据是以块的形式进行发送
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            // 对httpMessage进行聚合, 浏览器发送大数据时会发多个http请求，需要聚合起来
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            // websocket是以frame的方式发送和接收，frame是websocket中的一种
                            // 这个handler就是把http协议升级为websocket，http状态码101
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/chat"));
                            ch.pipeline().addLast(new MyWebSocketHandler());

                        }
                    })
                    .bind(8888)
                    .sync();
            log.info("server start");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server error", e);
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
